<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px" :inline="true">
    <el-form-item>
      <el-button type="primary" @click="toAdd">添加</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="constanttypecode" label="常数类别编码" width="180" />
    <el-table-column prop="constanttypename" label="常数类别名称" width="180" />
    <el-table-column label="操作" width="180">
      <template #default="scope">
        <el-button link type="primary" size="small" @click="toEdit(scope.row)">编辑</el-button>
        <el-button link type="danger" size="small" @click="remove(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="editDialogFormVisible" :title="dialogTitle" width="500">
    <el-form :model="editForm" label-width="auto">
      <el-form-item label="常数类别编码">
        <el-input v-model="editForm.constanttypecode" />
      </el-form-item>
      <el-form-item label="常数类别名称">
        <el-input v-model="editForm.constanttypename" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElNotification, ElMessageBox } from 'element-plus'
import service from '@/utils/request'

let form = ref({})
let tableData = ref([])
let editDialogFormVisible = ref(false)
let dialogTitle = ref('添加常数类别')

let editForm = ref({
  id: null,
  constanttypecode: '',
  constanttypename: ''
})

// 添加按钮
function toAdd() {
  dialogTitle.value = '添加常数类别'
  editForm.value = {
    id: null,
    constanttypecode: '',
    constanttypename: ''
  }
  editDialogFormVisible.value = true
}

// 编辑按钮
function toEdit(row) {
  dialogTitle.value = '编辑常数类别'
  editForm.value = { ...row } // 浅拷贝
  editDialogFormVisible.value = true
}

// 保存按钮（新增 / 修改）
function save() {
  const url = editForm.value.id ? '/constanttype/update' : '/constanttype/add'
  service.post(url, editForm.value).then(res => {
    if (res.data) {
      ElNotification({
        title: '成功',
        message: '保存成功',
        type: 'success'
      })
      editDialogFormVisible.value = false
      listData()
    } else {
      ElNotification({
        title: '失败',
        message: '保存失败',
        type: 'error'
      })
    }
  })
}

// 删除
function remove(id) {
  ElMessageBox.confirm('是否确认删除该常数类别？', '提示', {
    type: 'warning'
  })
      .then(() => {
        service.post('/constanttype/delete', { id }).then(res => {
          if (res.data) {
            ElNotification({
              title: '成功',
              message: '删除成功',
              type: 'success'
            })
            listData()
          }
        })
      })
      .catch(() => {})
}

// 获取数据
function listData() {
  service.get('/constanttype/list').then(res => {
    tableData.value = res.data
  })
}

onMounted(() => {
  listData()
})
</script>
